package com.ydd.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.github.pagehelper.Page;
import com.ydd.dto.CancelCollectionDTO;
import com.ydd.dto.MyArticleCollectionDTO;
import com.ydd.dto.PageQueryDTO;
import com.ydd.entity.Article;

import com.ydd.entity.UserData;


import com.github.pagehelper.PageHelper;
import com.ydd.context.BaseContext;
import com.ydd.context.BaseContext;
import com.ydd.dto.ArticleAddDTO;
import com.ydd.dto.ArticleListDTO;
import com.ydd.dto.ArticlePageDTO;
import com.ydd.dto.MyArticleCollectionDTO;
import com.ydd.entity.*;
import com.ydd.mapper.ArticleMapper;
import com.ydd.mapper.CateMapper;
import com.ydd.mapper.UserDataMapper;
import com.ydd.mapper.UserDataMapper;
import com.ydd.mapper.UserDataMapper;
import com.ydd.result.PageResult;
import com.ydd.mapper.CateMapper;

import com.ydd.service.IArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import com.ydd.vo.*;
import org.springframework.beans.BeanUtils;

import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;



import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hgz
 * @since 2023-05-30
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserDataMapper userDataMapper;

    /**
     * 我的文章分页查询
     *
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult getResult(PageQueryDTO pageQueryDTO,Integer userId) {

        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getLimit());
        //获取当前登录用户的文章集合
        List<Article> articleList  = articleMapper.getArticleList(userId);

        //分页处理
        Page page = (Page) articleList;
        PageResult pageResult = PageResult.builder()
                .count((int)page.getTotal())
                .pageSize(page.getPageSize())
                .totalPage(page.getPages())
                .currentPage(page.getPageNum())
                .data(page.getResult())
                .build();

        return pageResult;
    }

    /**
     * 收藏分页
     * @param myArticleCollectionDTO
     * @param userId
     * @return
     */
    @Override
    public PageResult getResultByCondition(MyArticleCollectionDTO myArticleCollectionDTO, Integer userId) {
        //获取用户收藏或点赞的文章id
        List<Integer> getArticleIds = userDataMapper.findByCondition(myArticleCollectionDTO.getType(),userId);

        if (getArticleIds.size() == 0){
            return null;
        }

        PageHelper.startPage(myArticleCollectionDTO.getPage(),myArticleCollectionDTO.getLimit());
        List<Article> articleList  = articleMapper.getCollectionArticleList(getArticleIds);

        List<MyCollectionVO> myCollectionVOList = new ArrayList<>();
        for (Article article : articleList) {
            Integer cateId = article.getCateid();
            String cateName = cateMapper.findById(cateId);
            MyCollectionVO myCollectionVO = new MyCollectionVO();
            BeanUtils.copyProperties(article,myCollectionVO);
            myCollectionVO.setCatename(cateName);
            myCollectionVO.setCreate_date(article.getCreateDate());
            myCollectionVOList.add(myCollectionVO);
        }

        //分页处理
        Page page = (Page) articleList;
        PageResult pageResult = PageResult.builder()
                .count((int)page.getTotal())
                .pageSize(page.getPageSize())
                .totalPage(page.getPages())
                .currentPage(page.getPageNum())
                .data(myCollectionVOList)
                .build();

        return pageResult;
    }

    /**
     * 点赞收藏、取消点赞收藏
     *
     * @param cancelCollectionDTO
     * @param userId
     * @return
     */
    @Override
    public void cancelCollection(CancelCollectionDTO cancelCollectionDTO, Integer userId) {

        String action = cancelCollectionDTO.getAction();

        Integer type = cancelCollectionDTO.getType();

        Integer articleid = cancelCollectionDTO.getArticle_id();

        //先判断是点赞还是收藏操作
        //type为1则为收藏操作
        if (type == 1){
            //action为add则为添加收藏
            if ("add".equals(action)){
                //将数据插入到userData表中
                UserData userData = UserData.builder()
                        .type(type)
                        .articleId(articleid)
                        .userId(userId)
                        .build();
                userDataMapper.insert(userData);
                //article表中的loveNum+1;
                articleMapper.loveNumPlus(articleid);
            } else {
                //将数据从userData表中删除
                QueryWrapper<UserData> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(userId !=null,UserData::getUserId, userId);
                wrapper.lambda().eq(articleid!=null,UserData::getArticleId,articleid);
                userDataMapper.delete(wrapper);

                //并将article表中的loveNum-1;
                articleMapper.loveNumMin(articleid);
            }
            //type为2则为点赞操作
        }else if (type == 2){
            //action为add则为添加点赞
            if ("add".equals(action)){
                //将数据插入到userData表中并将article表中的click+1;
                UserData userData = UserData.builder()
                        .type(type)
                        .articleId(articleid)
                        .userId(userId)
                        .build();
                userDataMapper.insert(userData);
                //article表中的click+1;
                articleMapper.clickPlus(articleid);
            } else {
                //将数据从userData表中删除
                QueryWrapper<UserData> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(userId !=null,UserData::getUserId, userId);
                wrapper.lambda().eq(articleid!=null,UserData::getArticleId,articleid);
                userDataMapper.delete(wrapper);

                //并将article表中的click-1;
                articleMapper.clickMin(articleid);
            }
        }
    }

    @Autowired
    private CateMapper cateMapper;

    /**
     * 热门置顶文章数据(首页)
     * @param begin
     * @param limit
     * @return6
     */
    @Override
    public NewInfoVO getNewInfo(Integer begin, Integer limit) {
        PageHelper.startPage(begin, limit);
        List<Article> articleList = articleMapper.page(null);
        com.github.pagehelper.Page page = (com.github.pagehelper.Page) articleList;

        //封装vo
        List<ArticleInfoVO> data = new ArrayList<>();
        articleList.forEach(article -> {
            ArticleInfoVO articleInfoVO = new ArticleInfoVO();
            BeanUtils.copyProperties(article, articleInfoVO);
            String catename = cateMapper.findById(article.getCateid());
            articleInfoVO.setCatename(catename);
            data.add(articleInfoVO);
        });

        //List list = new ArrayList();

        //获取24小时前的时间毫秒值
        Long dayBegin = LocalDateTime.now().minusDays(1).toInstant(ZoneOffset.of("+8")).toEpochMilli();
        //获取7天前的时间毫秒值
        Long weekBegin = LocalDateTime.now().minusDays(7).toInstant(ZoneOffset.of("+8")).toEpochMilli();

        Integer num_day = articleMapper.findByBeginTime(dayBegin);
        Integer num_week = articleMapper.findByBeginTime(weekBegin);
        return NewInfoVO.builder()
                .desc("首页大列表")
                .list(new PageResult((int)page.getTotal(),
                        page.getPages(),
                        page.getPageSize(),
                        page.getPageNum(),
                        page.getResult()))
                .num_day(num_day)
                .num_week(num_week)
                .build();
    }

    @Override
    public PageResult getArticleList(ArticlePageDTO articlePageDTO) {
        PageHelper.startPage(articlePageDTO.getPage(), articlePageDTO.getLimit());
        List<Article> articleList = articleMapper.page(articlePageDTO.getCateid());
        com.github.pagehelper.Page page = (com.github.pagehelper.Page) articleList;

        //封装vo
        List<ArticleInfoVO> data = new ArrayList<>();
        articleList.forEach(article -> {
            ArticleInfoVO articleInfoVO = new ArticleInfoVO();
            BeanUtils.copyProperties(article, articleInfoVO);
            String catename = cateMapper.findById(article.getCateid());
            articleInfoVO.setCatename(catename);
            data.add(articleInfoVO);
        });

        return new PageResult((int)page.getTotal(),
                page.getPages(),
                page.getPageSize(),
                page.getPageNum(),
                page.getResult());
    }

    @Override
    public ArticleShowVO show(Integer id) {
        //根据id查询文章数据
        Article article = articleMapper.selectById(id);

        //封装数据到ArticleInfoVO
        ArticleInfoVO info = new ArticleInfoVO();
        String userId = BaseContext.getCurrentId();

        if (userId==null){
            info.setIsLike(false);
            info.setIsCollect(false);
        }
        List<Integer> types = userDataMapper.findType(id, userId);

        if (types==null || types.size()==0){
            info.setIsLike(false);
            info.setIsCollect(false);
        }
        types.forEach(type -> {
            if (type == 1){
                info.setIsLike(true);
            }
            info.setIsLike(false);
        });

        BeanUtils.copyProperties(article, info);
        info.setCreate_date(article.getCreateDate());
        info.setDefault_data(article.getDefaultData());
        info.setUpdate_date(article.getUpdateDate());
        info.setUser_id(article.getUserId());
        String catename = cateMapper.findById(article.getCateid());
        info.setCatename(catename);

        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        //上一个文章
        queryWrapper.select("id","title").lt("id", id);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        PrevArticle prev = new PrevArticle();
        if (articles != null && articles.size() > 0){
            BeanUtils.copyProperties(articles.get(0), prev);
        }
        List<PrevArticle> prevArticleList = new ArrayList<>();
        prevArticleList.add(prev);

        QueryWrapper<Article> queryWrapper2 = new QueryWrapper<>();
        //下一篇文章
        queryWrapper2.select("id","title").gt("id", id);
        List<Article> articles1 = articleMapper.selectList(queryWrapper2);
        NextArticle next = new NextArticle();
        if (articles1 != null && articles1.size() > 0){
            BeanUtils.copyProperties(articles1.get(0), next);
        }
        List<NextArticle> nextArticleList = new ArrayList<>();
        nextArticleList.add(next);

        QueryWrapper<Article> queryWrapper3 = new QueryWrapper<>();
        //推荐文章
        queryWrapper3.select("id","cateid","title","pic").ge("istop", 1);
        List<Article> articleList = articleMapper.selectList(queryWrapper3);
        List<RecommendArticle> recommend = new ArrayList<>();
        articleList.forEach(article1 -> {
            RecommendArticle recommendArticle = new RecommendArticle();
            BeanUtils.copyProperties(article1, recommendArticle);
            Cate cate = cateMapper.selectById(article1.getCateid());
            if (cate != null){
                recommendArticle.setCatename(cate.getCatename());
                recommend.add(recommendArticle);
            }
        });

        return ArticleShowVO.builder()
                .info(info)
                .prev(prevArticleList)
                .next(nextArticleList)
                .recommend(recommend)
                .build();
    }

    /**
     * 最新文章
     * @return
     */
    @Override
    public ArticleResult hot() {
        List<HotArticleVO> list = articleMapper.list();
        list.forEach(hotArticleVO -> {
            String name = cateMapper.findById(hotArticleVO.getId());
            hotArticleVO.setCatename(name);
        });

        return ArticleResult.builder()
                .desc("侧边最新文章")
                .list(list)
                .build();
    }

    @Override
    public ArticleResult recommend() {
        List<HotArticleVO> list = articleMapper.hotList();
        list.forEach(hotArticleVO -> {
            String name = cateMapper.findById(hotArticleVO.getId());
            hotArticleVO.setCatename(name);
        });

        return ArticleResult.builder()
                .desc("侧边推荐文章")
                .list(list)
                .build();
    }

    /**
     * 发布文章
     *
     * @param article
     * @param userId
     */
    @Override
    public void insert(Article article, Integer userId) {

        article.setUserId(userId);



    }


    /**
     * 分页列表查询
     * @param articleListDTO
     * @return
     */
    @Override
    public ArticleListVO pageList(ArticleListDTO articleListDTO) {
        PageHelper.startPage(articleListDTO.getPage(),articleListDTO.getLimit());
        List<AritllllllVO> aritllllllVOS= articleMapper.select(articleListDTO);
        aritllllllVOS.forEach(aritllllllVO -> {
            aritllllllVO.setCatename(cateMapper.selectNameById(aritllllllVO.getCateid()));
            aritllllllVO.setCreate_date(aritllllllVO.getCreateDate());
        });

        com.github.pagehelper.Page page=(com.github.pagehelper.Page) aritllllllVOS;

        return ArticleListVO.builder()
                .count((int) page.getTotal())
                .totalPages(page.getPages())
                .pageSize(page.getPageSize())
                .currentPage(page.getPageNum())
                .data(page.getResult())
                .build();
    }

    @Override
    public void add(ArticleAddDTO articleAddDTO) {
        Article article = new Article();
        BeanUtils.copyProperties(articleAddDTO,article);
        article.setCreateDate(articleAddDTO.getCreate_date());
        article.setUserId(Integer.parseInt(BaseContext.getCurrentId()));
        article.setUpdateDate(articleAddDTO.getCreate_date());
        articleMapper.insert(article);
    }


}
